package br.com.foxline.atlasmobile.novocadastro;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import br.com.foxline.atlasmobile.CreateMainActivity;
import br.com.foxline.atlasmobile.DadosFamiliaresActivity;
import br.com.foxline.atlasmobile.LocalizacaoActivity;
import br.com.foxline.atlasmobile.MenuActivity;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.dao.ImovelDao;
import br.com.foxline.atlasmobile.dao.ProprietarioDao;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.enums.SituacaoImovel;
import br.com.foxline.atlasmobile.util.CnpjValidator;
import br.com.foxline.atlasmobile.util.CpfValidator;

@SuppressLint("NewApi")
public class AddCidadaoActivity extends Activity {

	private static String IMOVEL = "getimovel";

	// DAO
	private ImovelDao imovelDao;

	private ProprietarioDao proprietarioDao;

	private Imovel imovel;

	private Proprietario proprietario;
	private Proprietario proprietarioRemove;

	private List<Proprietario> proprietarios;

	private EditText cpf;

	private EditText nome;

	private EditText rg;

	private EditText orgaoemissor;

	private EditText datanascimento;

	private EditText profissao;
	
	private EditText telefones;
	
	private EditText conjuge;
	
	private EditText cpfConjuge;

	private ListView list;

	private ProprietarioArrayAdapter arrayAdapter;

	private AlertDialog rankDialog;
	private AlertDialog removeDialog;
	
	private Spinner estadoCivil;

	private OnItemLongClickListener longListener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			proprietarioRemove = arrayAdapter.getItem(arg2);
			removeDialog.show();
			return false;
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_cidadao);

		nome = (EditText) findViewById(R.id.nome_proprietario);
		cpf = (EditText) findViewById(R.id.cpf_proprietario);
		rg = (EditText) findViewById(R.id.edit_rg);
		profissao = (EditText) findViewById(R.id.edit_profissao);
		orgaoemissor = (EditText) findViewById(R.id.edit_emissor);
		datanascimento = (EditText) findViewById(R.id.edit_datanascimento);
		
		estadoCivil = (Spinner) findViewById(R.id.spinner_estado_civil);
		telefones = (EditText) findViewById(R.id.edit_telefone);
		conjuge = (EditText) findViewById(R.id.edit_conjuge);
		cpfConjuge = (EditText) findViewById(R.id.edit_cpf_conjuge);

		// TODO
		list = new ListView(getApplicationContext());

		proprietarios = new ArrayList<Proprietario>();
		proprietario = new Proprietario();

		if (getIntent().getSerializableExtra(IMOVEL) != null) {

			imovelDao = new ImovelDao(getApplicationContext());
			imovel = (Imovel) getIntent().getSerializableExtra(IMOVEL);

			proprietarioDao = new ProprietarioDao(getApplicationContext());

			if (imovel.getProprietarios() != null) {
				proprietarios = new ArrayList<Proprietario>();
				for (Proprietario proprietario : imovel.getProprietarios()) {
					proprietarios.add(proprietario);
				}
			} else {
				proprietarios = new ArrayList<Proprietario>();
			}

		} else {
			imovel = new Imovel();
			proprietario = new Proprietario();
			proprietarios = new ArrayList<Proprietario>();
		}

		arrayAdapter = new ProprietarioArrayAdapter(getApplicationContext(),
				R.layout.proprietario_item, proprietarios);
		list.setAdapter(arrayAdapter);
		
		//SETA ESTADO CIVIL
		
        List<String> list = new ArrayList<String>();
        list.add("Solteiro(a)");
        list.add("Casado(a)");
        list.add("Divorciado(a)");
        list.add("Viúvo(a)");
        list.add("União estável");
        list.add("Outro");
         
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                     (this, android.R.layout.simple_spinner_item,list);
                      
        dataAdapter.setDropDownViewResource
                     (android.R.layout.simple_spinner_dropdown_item);
                      
        estadoCivil.setAdapter(dataAdapter);
        

		criarDialog();
		criarDialogRemover();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getActionBar().setHomeButtonEnabled(true);
		getMenuInflater().inflate(R.menu.add_cidadao, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		boolean cancel = false;
		switch (item.getItemId()) {
		case R.id.btn_add_proprietario:
			if (nome.getText().toString().equals("")) {
				exibeMensagem("Nome é obrigatório");
				cancel = true;
				break;
			}
			proprietario.setNome(nome.getText().toString());

			if (cpf.getText().toString().length() == 11) {
				if (CpfValidator.isValid(cpf.getText().toString())) {
					proprietario.setCpf(cpf.getText().toString());
				} else {
					exibeMensagem("CPF Inválido");
					cancel = true;
					break;
				}
			} else if (cpf.getText().toString().length() == 14) {
				if (CnpjValidator.isValid(cpf.getText().toString())) {
					proprietario.setCpf(cpf.getText().toString());
				} else {
					exibeMensagem("CNPJ Inválido");
					cancel = true;
					break;
				}
			}

			proprietario.setRg(rg.getText().toString());
			proprietario.setOrgaoEmissor(orgaoemissor.getText().toString());
			proprietario.setProfissao(profissao.getText().toString());
			
			//ATUALIZACAO DE ESTADO CIVIL, TELEFONE, CONJUGE
			proprietario.setEstadoCivil(String.valueOf(estadoCivil.getSelectedItem()));
			proprietario.setTelefone(telefones.getText().toString());
			proprietario.setConjuge(conjuge.getText().toString());
			
			if (cpfConjuge.getText().toString().length() > 0) {
				if (CpfValidator.isValid(cpfConjuge.getText().toString())) {
					proprietario.setCpfConjuge(cpfConjuge.getText().toString());
				} else {
					exibeMensagem("CPF do cônjuge inválido");
					cancel = true;
					break;
				}
			}
			
			
			SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");

			try {
				if (!datanascimento.getText().toString().isEmpty())
					proprietario.setDataNasc(format.parse(datanascimento
							.getText().toString()));
			} catch (ParseException e) {
				e.printStackTrace();
				exibeMensagem("Data Inválida");
				cancel = true;
				break;
			}

			if (!cancel) {
				proprietarios.add(proprietario);

				arrayAdapter.notifyDataSetChanged();

				nome.setText("");
				cpf.setText("");
				rg.setText("");
				orgaoemissor.setText("");
				datanascimento.setText("");
				profissao.setText("");
				telefones.setText("");
				conjuge.setText("");
				cpfConjuge.setText("");

				proprietario = new Proprietario();
				onBackPressed();

			}
			break;
		case R.id.show_proprietario:
			showProprietarios();
			break;
		case R.id.finalizar:
			dialogSituacao();
			break;
		default: onBackPressed() ;
		}
		return super.onOptionsItemSelected(item);
	}

	public void criarDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(" Proprietários ou Detentores");
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		LayoutInflater inflater = this.getLayoutInflater();
		View inflate = inflater.inflate(R.layout.proprietarios, null);

		builder.setView(inflate);

		ListView listView = (ListView) inflate.findViewById(R.id.listView1);
		listView.setAdapter(list.getAdapter());

		listView.setOnItemLongClickListener(longListener);

		rankDialog = builder.create();

	}

	public void criarDialogRemover() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(" Remover Proprietário");
		builder.setMessage(" Desejar remover o proprietário do cadastro ?");
		builder.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				arrayAdapter.remove(proprietarioRemove);
				proprietarios.remove(proprietarioRemove);
				if (proprietarioRemove.getId() != null)
					proprietarioDao.delete(proprietarioRemove);
				save();
				exibeMensagem("Proprietário Removido com Sucesso !");

			}
		});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		removeDialog = builder.create();

	}

	public void showProprietarios() {

		rankDialog.show();
	}

	public void save() {
		proprietarioDao = new ProprietarioDao(getApplicationContext());

		for (Proprietario pro : proprietarios) {
			if (pro.getId() == null) {
				pro.setImovel(imovel);
				proprietarioDao.create(pro);
			} else {
				pro.setImovel(imovel);
				proprietarioDao.update(pro);
			}
		}

		imovelDao.update(imovel);
		imovel = imovelDao.find(imovel.getId());

	}

	public Integer parseInt(String str) {
		try {
			return (Integer.parseInt(str));
		} catch (Exception e) {
			return null;
		}

	}

	public void next(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				DadosFamiliaresActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		finish();
	}

	public void previous(View view) {
		save();
		Intent intent = new Intent(getApplicationContext(),
				LocalizacaoActivity.class);
		intent.putExtra(IMOVEL, imovel);
		startActivity(intent);
		finish();
	}

	private void exibeMensagem(String msg) {
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
	}

	private class ProprietarioArrayAdapter extends ArrayAdapter<Proprietario> {

		private List<Proprietario> list;

		public ProprietarioArrayAdapter(Context context,
				int textViewResourceId, List<Proprietario> objects) {
			super(context, textViewResourceId, objects);

			if (objects == null)
				list = new ArrayList<Proprietario>();
			list = objects;

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Proprietario getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return super.getItemId(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return super.getView(position, convertView, parent);
		}
	}

	public void dialogSituacao() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Situação do Imóvel");

		final String[] items = new String[SituacaoImovel.values().length];
		int cont = 0;
		final Map<Integer, SituacaoImovel> map = new HashMap<Integer, SituacaoImovel>();

		for (SituacaoImovel si : SituacaoImovel.values()) {
			items[cont] = si.toString();
			map.put(cont, si);
			cont++;
		}

		builder.setItems(items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				imovel.setSituacaoImovel(map.get(which));
				save();
				imovel.getSituacaoImovel();
				finalCadastro();
			}
		});

		AlertDialog dsituacao = builder.create();
		dsituacao.show();
	}

	public void finalCadastro() {

		AlertDialog dialog;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setNeutralButton("Finalizar e usar como modelo",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								CreateMainActivity.class);

						imovel.setId(null);

						if (imovel.getEnderecoImovel() != null)
							imovel.getEnderecoImovel().setId(null);
						if (imovel.getEnderecoCorrespondencia() != null)
							imovel.getEnderecoCorrespondencia().setId(null);
						if (imovel.getAnnex() != null) {
							imovel.setAnnex(null);
						}
						if (imovel.getDimensoes() != null) {
							imovel.getDimensoes().setId(null);
						}
						if (imovel.getProprietarios() != null) {
							for (Proprietario p : imovel.getProprietarios()) {
								p.setId(null);
							}
						}

						intent.putExtra(IMOVEL, imovel);

						startActivity(intent);
						finish();

					}
				});

		builder.setPositiveButton("Finalizar",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						Intent intent = new Intent(getApplicationContext(),
								MenuActivity.class);
						startActivity(intent);
						finish();

					}
				});

		builder.setNegativeButton("Não", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {

			}
		});

		builder.setMessage("Desejar finalizar o cadastro").setTitle(
				"Cadastro Finalizado");

		dialog = builder.create();
		dialog.show();
	}
}